'use strict';

const Controller = require('egg').Controller;

class HomeController extends Controller {
  async index() {
    const result = await this.app.mysql.get('blog_content', {});
    this.ctx.body = {
      data: result,
    };
  }
  // 获取类别名称和编号
  async getTypeInfo() {
    const result = await this.app.mysql.select('type');
    this.ctx.body = { data: result };
  }
  // 根据类别ID获得文章列表
  async getArticleList() {
    const sql = `SELECT article.id as id,
      article.title as title,
      article.introduce as introduce,
      FROM_UNIXTIME(article.created_at, '%Y-%m-%d %H:%i:%s') as created_at,
      article.view_count as view_count,
      type.type_name as type_name FROM article LEFT JOIN type ON article.type_id = type.id`;
    const result = await this.app.mysql.query(sql);
    this.ctx.body = { data: result };
  }
  // 根据类别ID获得文章列表
  async getListById() {
    const id = this.ctx.params.id;
    const sql = `SELECT article.id as id,
      article.title as title,
      article.introduce as introduce,
      FROM_UNIXTIME(article.created_at, '%Y-%m-%d %H:%i:%s') as created_at,
      article.view_count as view_count,
      type.type_name as type_name FROM article LEFT JOIN type ON article.type_id = type.id WHERE article.type_id=${id}`;
    const result = await this.app.mysql.query(sql);
    this.ctx.body = { data: result };
  }
  // 获取文章详情
  async getArticleById() {
    const id = this.ctx.params.id;
    const sql = `SELECT article.id as id,
      article.title as title,
      article.introduce as introduce,
      article.article_content as article_content,
      FROM_UNIXTIME(article.created_at, '%Y-%m-%d %H:%i:%s') as created_at,
      article.view_count as view_count,
      type.type_name as type_name FROM article LEFT JOIN type ON article.type_id = type.id WHERE article.id=${id}`;
    const result = await this.app.mysql.query(sql);
    this.ctx.body = { data: result };
  }
}

module.exports = HomeController;
